package com.example.SMS;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.ChoiceBox;
import javafx.stage.Stage;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class RegisterController {
    @FXML
    private Hyperlink backToLoginLink;
    private Stage stage;
    private Scene loginScene;

    @FXML
    private javafx.scene.control.TextField register_tel;
    @FXML
    private javafx.scene.control.TextField register_oncampusID;
    @FXML
    private javafx.scene.control.TextField register_pwd;
    @FXML
    private javafx.scene.control.TextField register_pwd_check;
    @FXML
    private ChoiceBox<String> register_type;

    public void setStage(Stage stage) {
        this.stage = stage;
    }

    public void setLoginScene(Scene loginScene) {
        this.loginScene = loginScene;
    }

    @FXML
    private void handleBackToLoginClick(ActionEvent event) {
        if (stage != null && loginScene != null) {
            stage.setScene(loginScene);
        }
    }

    // 在 initialize() 方法中移除重复初始化代码
    @FXML
    public void initialize() {
        // 只需保留监听器（FXML中已初始化选项）
        register_type.getSelectionModel().selectedItemProperty().addListener(
                (observable, oldValue, newValue) -> {
                    System.out.println("选中了: " + newValue);
                }
        );
    }


    private void showAlert(AlertType type, String title, String message) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    // 清空所有输入框的方法
    private void clearInputFields() {
        register_tel.clear();
        register_oncampusID.clear();
        register_pwd.clear();
        register_pwd_check.clear();
        register_type.getSelectionModel().clearSelection();
    }

    @FXML
    private void handleRegister(ActionEvent event) {
        String tel = register_tel.getText().trim();
        String oncampusID = register_oncampusID.getText().trim();
        String password = register_pwd.getText().trim();
        String pwd_check = register_pwd_check.getText().trim();
        String userType = register_type.getValue().trim();

        // 验证必填字段
        if (tel.isEmpty() || password.isEmpty() || pwd_check.isEmpty() || userType == null || userType.equals("请选择用户类型")) {
            showAlert(AlertType.WARNING, "警告", "除学号/工号外所有字段必须填写或选择");
            return;
        }

        // 检查密码是否一致
        if (!password.equals(pwd_check)) {
            showAlert(AlertType.ERROR, "错误", "两次输入的密码不一致，请重新输入");
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            // 注册新用户
            String sqlInsert = "INSERT INTO userinformation (tel,oncampusID,pwd,usertype) VALUES (?,?,?,?)";
            try (PreparedStatement pstmtInsert = conn.prepareStatement(sqlInsert)) {
                pstmtInsert.setString(1, tel);
                pstmtInsert.setString(2, oncampusID);
                pstmtInsert.setString(3, password);
                pstmtInsert.setString(4, userType);

                int rows = pstmtInsert.executeUpdate();
                if (rows > 0) {
                    showAlert(AlertType.INFORMATION, "成功", "注册成功！即将返回登录界面...");
                    clearInputFields(); // 清空输入框

                    // 使用Platform.runLater确保UI更新在主线程执行
                    javafx.application.Platform.runLater(() -> {
                        try {
                            Thread.sleep(1000); // 1秒延迟
                            if (stage != null && loginScene != null) {
                                stage.setScene(loginScene);
                            }
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    });
                }
            } catch (SQLException e) {
                showAlert(AlertType.ERROR, "数据库错误", "注册失败: " + e.getMessage());
                e.printStackTrace();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
